<?php


namespace app\admin\service\Admin;


use think\exception\ValidateException;
use think\response\Json;

class Role
{
    /**
     * 角色菜单
     * @return Json
     */
    public function getRoleMenus(){
        $menu = self::getNodeMenus(1,0);
        $order_array = array_column($menu, 'sortid');
        array_multisort($order_array,SORT_ASC,$menu );
        return $menu;
    }
    /**
     * 权限系统获取菜单
     * @param $app_id
     * @param $pid
     * @return array
     */
    private function getNodeMenus($app_id,$pid){
        try{
            $field = 'menu_id,title,controller_name,status,icon,sortid';
            $list = db('sys_menu')
                ->field($field)
                ->where(['app_id'=>$app_id,'pid'=>$pid])
                ->order('sortid asc')
                ->select()
                ->toArray();
            if($list){
                foreach($list as $key=>$val){
                    $menus[$key]['sortid'] = $val['sortid'];
                    $menus[$key]['access'] = $val['controller_name'];
                    $menus[$key]['title'] = $val['title'].' '.'(/admin/'.$val['controller_name'].')';
                    $sublist = db('sys_menu')
                        ->field($field)
                        ->where(['app_id'=>$app_id,'pid'=>$val['menu_id']])
                        ->order('sortid asc')
                        ->select()
                        ->toArray();
                    if($sublist){
                        if($this->getFuns($val)){
                            $menus[$key]['children'] = array_merge($this->getFuns($val),$this->getNodeMenus($app_id,$val['menu_id']));
                        }else{
                            $menus[$key]['children'] = $this->getNodeMenus($app_id,$val['menu_id']);
                        }
                    }else{
                        $funs = $this->getFuns($val);
                        $funs && $menus[$key]['children'] = $funs;
                    }
                }
                return array_values($menus);
            }
        } catch (\Exception $e){
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 获取菜单方法
     * @param $info
     * @return array
     */
    private function getFuns($info){
        try {
            $list = db('sys_action')
                ->field('name,action_name')
                ->where('menu_id',$info['menu_id'])
                ->order('sortid asc')
                ->select()
                ->toArray();
            if($list){
                foreach($list as $key=>$val){
                    $funs[$key]['title'] = $val['name'].' '.(string)url('admin/'.$info['controller_name'].'/'.$val['action_name']);
                    $funs[$key]['access'] = (string)url('admin/'.$info['controller_name'].'/'.$val['action_name']);
                }
                return array_values($funs);
            }
        } catch (\Exception $e){
            throw new ValidateException($e->getMessage());
        }
    }
}